// pages/login/login.js
import {
  HttpApi
} from '../../../model/index.js'
const httpApi = new HttpApi

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		showBindMobileNo: false,
		hidden: true,
		btnValue: '',
		btnDisabled: false,
		name: '',
		phone: '',
		code: '',
		second: 60,
		openid: "",
		unionid: ""
	},
	onLoad(){
		var hasLogin = wx.getStorageSync('hasLogin')
		if(hasLogin){
			this.login()
		}
	},
	getDict(){
		httpApi.getDict().then(res => {			
			if (res.code == 0) {
				var dict = new Array()
				var dictArr = res.data				
				for (var i=0;i<dictArr.length;i++){
					var subDict = new Array()
					var subDictArr = dictArr[i].dictDatas
					for (var j=0;j<subDictArr.length;j++){
						subDict[subDictArr[j].val] = subDictArr[j].label
					}
					dict[dictArr[i].name] = subDict					
				}
				console.log("dict:",dict)
				//wx.setStorageSync('dict', dict)
				var app = getApp()
				app.globalData.dict = dict
			}
		})
	},
	loginin(code){
		var _this = this;
		//调用登录接口
		httpApi.code2session(code).then(res => {
			if (res.code == 200) {
				wx.hideLoading()
				if (!res.token || res.token == "") {
					wx.navigateTo({
            url: "../register/register"
					})
				} else {
					//缓存token
					wx.setStorageSync('token', res.token)
					wx.navigateTo({
            url: "../../home"
					})
				} wx.setStorageSync('login', "OK")
					wx.setStorageSync('openid', res.openid);		
			}
		})
	},
	/* wx登录 */
	login() {		
		var _this = this;
		wx.login({
			success(res) {
				wx.showLoading({
					title: '登录中',
				})
				if (res.code) {
					wx.setStorageSync('hasLogin', true)					
					_this.loginin(res.code)
				} else {
          wx.navigateTo({
            url: "../../home"
          })
					wx.showToast({
						title: "登录失败",
						icon: "none"
					})
				}
			}
		})
	},

	//手机号输入
	bindPhoneInput(e) {
		console.log(e.detail.value);
		var val = e.detail.value;
		this.setData({
			phone: val
		})
		if (val != '') {
			this.setData({
				hidden: false,
				btnValue: '获取验证码'
			})
		} else {
			this.setData({
				hidden: true
			})
		}
	},
	//验证码输入
	bindCodeInput(e) {
		this.setData({
			code: e.detail.value
		})
	},
	//获取短信验证码
	getCode(e) {
		console.log('获取验证码');
		console.log(this.data.phone)
		var that = this;
		wx.showLoading({
			title: '获取验证码中',
		})
		//调用登录接口
		httpApi.msgcode(this.data.phone).then(res => {
			if (res.code == 0) {
				wx.hideLoading()
				that.timer();
			}
		})
	},

	bindToRegister() {
		// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框						
		var _this = this;
		wx.getUserInfo({
			success: res => {
				// 可以将 res 发送给后台解码出 unionId
				// this.globalData.userInfo = res.userInfo
				console.log("getuserinfo:", res);
				httpApi.register(_this.data.openid, res.userInfo.nickName, res.userInfo.gender, res.userInfo.city, res.userInfo
					.country, res.userInfo.province, res.userInfo.avatarUrl, _this.data.unionid, _this.data.phone, _this.data.code
				).then(res => {
					if (res.code == 0) {
						console.log("register res:", res)
						wx.setStorageSync('token', res.data)
						_this.getDict()
						wx.navigateTo({
							url: "../u_select_community/u_select_community"
						})
					}
				})

				// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
				// 所以此处加入 callback 以防止这种情况
				if (this.userInfoReadyCallback) {
					this.userInfoReadyCallback(res)
				}
			}
		})
	},


	timer: function() {
		let promise = new Promise((resolve, reject) => {
			let setTimer = setInterval(
				() => {
					var second = this.data.second - 1;
					this.setData({
						second: second,
						btnValue: second + '秒',
						btnDisabled: true
					})
					if (this.data.second <= 0) {
						this.setData({
							second: 60,
							btnValue: '获取验证码',
							btnDisabled: false
						})
						resolve(setTimer)
					}
				}, 1000)
		})
		promise.then((setTimer) => {
			clearInterval(setTimer)
		})
	},
})
